import { parseTime } from './ruoyi'
import { ElMessage } from 'element-plus'

/**
 * 表格时间格式化
 */
export function formatDate(cellValue) {
  if (cellValue == null || cellValue == "") return "";
  var date = new Date(cellValue)
  console.log(date)
  var year = date.getFullYear()
  var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xDC00 && code <= 0xDFFF) i--
  }
  return s
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + ''
  const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  return (+(randomNum + timestamp)).toString(32)
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

export function makeMap(str, expectsLowerCase) {
  const map = Object.create(null)
  const list = str.split(',')
  for (let i = 0; i < list.length; i++) {
    map[list[i]] = true
  }
  return expectsLowerCase
    ? val => map[val.toLowerCase()]
    : val => map[val]
}

export const exportDefault = 'export default '

export const beautifierConf = {
  html: {
    indent_size: '2',
    indent_char: ' ',
    max_preserve_newlines: '-1',
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: 'separate',
    brace_style: 'end-expand',
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: false,
    end_with_newline: true,
    wrap_line_length: '110',
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true
  },
  js: {
    indent_size: '2',
    indent_char: ' ',
    max_preserve_newlines: '-1',
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: 'normal',
    brace_style: 'end-expand',
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: true,
    end_with_newline: true,
    wrap_line_length: '110',
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true
  }
}

// 首字母大小
export function titleCase(str) {
  return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
}

// 下划转驼峰
export function camelCase(str) {
  return str.replace(/_[a-z]/g, str1 => str1.substr(-1).toUpperCase())
}

export function isNumberStr(str) {
  return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
}
/**
* @description 生成唯一 uuid
* @return string
*/
export function generateUUID() {
  if (typeof crypto === 'object') {
    if (typeof crypto.randomUUID === 'function') {
      return crypto.randomUUID()
    }
    if (
      typeof crypto.getRandomValues === 'function' &&
      typeof Uint8Array === 'function'
    ) {
      const callback = (c) => {
        const num = Number(c)
        return (
          num ^
          (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (num / 4)))
        ).toString(16)
      }
      return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, callback)
    }
  }
  let timestamp = new Date().getTime()
  let performanceNow =
    (typeof performance !== 'undefined' &&
      performance.now &&
      performance.now() * 1000) ||
    0
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    let random = Math.random() * 16
    if (timestamp > 0) {
      random = (timestamp + random) % 16 | 0
      timestamp = Math.floor(timestamp / 16)
    } else {
      random = (performanceNow + random) % 16 | 0
      performanceNow = Math.floor(performanceNow / 16)
    }
    return (c === 'x' ? random : (random & 0x3) | 0x8).toString(16)
  })
}
// 表单重置
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields()
  }
}
// copy
export function copy(data) {
  let formattedData = data.replace(/\n/g, '\r\n'); // Replace \n with \r\n for Windows newline
  let oInput = document.createElement('textarea'); // Use textarea instead of input for multiline content
  oInput.value = formattedData;
  document.body.appendChild(oInput);
  oInput.select(); // Select the textarea's content
  document.execCommand("Copy"); // Execute the browser's copy command
  ElMessage.success('复制成功');
  oInput.remove();
}

// 只能输入数字
export function replaceNumber(event) {
  const input = event.target;
  input.value = input.value.replace(/[^0-9.]/g, '');
}

// 只能输入小数点后两位
export function replaceRadixPoint(value) {
  return value.replace(/[^0-9.]/g, '')
}

// 图片排序
export function photoSort(row, list) {
  let array = deepClone(list);
  let index = list.indexOf(row);
  if (index !== -1) {
    let itemsBefore = array.splice(0, index);
    array.push(...itemsBefore);
  }
  return array;
}

// 图片排序
export function photoSort01(row, list) {
  let array = deepClone(list)
  let index = list.findIndex(i => i.image_link == row.image_link);
  if (index !== -1) {
    var item = array.splice(index, 1);
    array.unshift(item[0]);
  }
  return array
}
/**
 * 是否小于当前-天
 * @param time Data对象
 * @returns {boolean}
 * @constructor
 */
export function UtilEleDisabledDay(time) {
  return time.getTime() < Date.now() - 8.64e7;
}

/**
 * 是否小于当前-小时
 * @returns {*[]}
 * @constructor
 */
export function UtilEleDisabledHour() {
  const arrs = []
  for (let i = 0; i < 24; i++) {
    if (new Date().getHours() <= i) continue
    arrs.push(i)
  }
  return arrs
}

/**
 * 是否小于当前-分
 * @returns {*[]}
 * @constructor
 */
export function UtilEleDisabledMinute() {
  const arrs = []
  for (let i = 0; i < 60; i++) {
    if (new Date().getMinutes() <= i) continue
    arrs.push(i)
  }
  return arrs
}

/**
 * 是否小于当前-秒
 * @returns {*[]}
 * @constructor
 */
export function UtilEleDisabledSecond() {
  const arrs = []
  for (let i = 0; i < 60; i++) {
    if (new Date().getSeconds() <= i) continue
    arrs.push(i)
  }
  return arrs
}

/**
 * 根据userIds匹配组织架构的人员姓名
 * @param data
 * @param ids
 * @returns {{}}
 * @constructor
 */
export function UtilMatchPersonName(data, userIds = []) {
  const result = {}
  for (const item of data) {
    const { user_id, sub, name } = item
    if (userIds.includes(user_id)) {
      result[user_id] = name
      if (Object.keys(result).length === userIds.length) break
    } else {
      if (sub && Array.isArray(sub)) {
        Object.assign(result, UtilMatchPersonName(sub, userIds))
      }
    }
  }
  return result
}

/**
 * @param {Array} 
 * @returns {Array}
 */
export function getCurrentDayNumber() {
  const date = new Date();
  var year = date.getFullYear()
  var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  // 将获取的年、月、日组合成日期字符串
  const formattedDate = `${year}-${month}-${day}`;
  return formattedDate
}


export function getImageSize(imageUrl) {
  return new Promise((resolve) => {
    const img = new Image();
    img.onload = function () {
      resolve({ width: this.width, height: this.height });
    };
    img.src = imageUrl;
  });
}

// 数据权限
export function dataAuthority(auth, val) {
  return (window.BTN_AUTH || []).includes(auth)
  // if ((window.BTN_AUTH || []).includes(auth)) {
  //   return val
  // } else {
  //   return '**'
  // }
}

// 获取当月的第一天
export function getFirstDayOfMonthString(data) {
  const date = new Date(data)
  const firstDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1);
  return firstDayOfMonth;
}

// 获取当月的最后一天
export function getLastDayOfMonthString(data) {
  const date = new Date(data)
  const lastDayOfMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0);
  return lastDayOfMonth
}

// 打开外部链接
export function openLink(link) {
  if (!link) return false
  if (link.indexOf("http") != -1) {
    window.open(link, "_blank")
  } else {
    window.open(`https://${link}`, "_blank")
  }
}

export function getCurrentWeek() {
  const today = new Date();
  // 获取当前时区偏移量，以分钟为单位
  const timeZoneOffset = today.getTimezoneOffset();
  // 调整为北京时间
  const chinaTime = new Date(today.getTime() - (timeZoneOffset * 60 * 1000) + (8 * 60 * 60 * 1000));
  const firstDayOfWeek = new Date(chinaTime.getFullYear(), chinaTime.getMonth(), chinaTime.getDate() - (chinaTime.getDay() === 0 ? 6 : chinaTime.getDay() - 1));
  var year = firstDayOfWeek.getFullYear()
  var month = firstDayOfWeek.getMonth() + 1 < 10 ? '0' + (firstDayOfWeek.getMonth() + 1) : firstDayOfWeek.getMonth() + 1
  var day = firstDayOfWeek.getDate() < 10 ? '0' + firstDayOfWeek.getDate() : firstDayOfWeek.getDate()
  // 将获取的年、月、日组合成日期字符串
  const formattedDate = `${year}-${month}-${day}`;
  return formattedDate
}

export function findUrlInList(data, targetUrl) {
  // 遍历列表
  for (const item of data) {
    // 检查当前项的URL是否与目标URL匹配
    if (item.url === targetUrl) {
      return item; // 找到匹配的URL，返回该项
    }
    // 如果当前项有子项，则递归调用自己在子项中查找
    if (item.sub && item.sub.length > 0) {
      const foundItem = findUrlInList(item.sub, targetUrl);
      if (foundItem) {
        return true; // 找到匹配的URL，返回该项
      }
    }
  }
  // 如果没有找到匹配的URL，则返回null
  return false;
}

export function filterDeleteFlag(array = []) {
  const nonDeletedItems = array.filter(
    (item) => !('delete' in item) || (item.delete !== 1)
  );
  return nonDeletedItems.length === 1;
}

export function isURL(url) {
  const pattern = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;
  return pattern.test(url);
}

export async function isLinkValid(url) {
  if (!isURL(url)) {
    console.error(`Invalid URL format: ${url}`);
    return false;
  }
  try {
    const response = await fetch(url, { method: 'HEAD' }); // 使用HEAD方法减少数据传输
    return response.ok; // 如果状态码在200-299之间，则返回true，否则返回false
  } catch (error) {
    console.error(`Error checking URL: ${url}`, error);
    return false; // 发生网络错误或其他异常时，认为链接失效
  }
}

// 创建一个函数来验证并转换为数字，同时处理无效输入的情况
export function toNumber(value, defaultValue = 0) {
  const num = Number(value);
  return isNaN(num) ? defaultValue : num;
}

export function isPermission(auth) {
  if (!auth) return true;
  return (window.BTN_AUTH || []).includes(auth);
}

export function getDateFromTimestamp() {
  const date = new Date(getDateFromTimestamp);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  return `${year}-${month}`;
}


// 获取上个月初始日期
export function getLastDayNumber() {
  const date = new Date();
  var year = date.getFullYear()
  var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth()) : date.getMonth() + 1
  var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  // 将获取的年、月、日组合成日期字符串
  const formattedDate = `${year}-${month}-${day}`;
  return formattedDate
}

export const $auth = (val) => val ? (window.BTN_AUTH || []).includes(val) : true


// 处理月份显示
export function formatMonth(start, end) {
  if (start && end) {
    if (start == end) {
      return `${start}月`;
    } else {
      return `${start}-${end}月`;
    }
  } else if (start) {
    return `${start}月`;
  } else if (start) {
    return `${end}月`;
  }
};

// 获取上当月初始日期
export function getNowMonthDay() {
  const date = new Date();
  var year = date.getFullYear()
  console.log(date.getMonth())
  var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  // 将获取的年、月、日组合成日期字符串
  const formattedDate = `${year}-${month}-${day}`;
  return formattedDate
}

// 删除id sku_id spu_id
export function removeIds(obj) {
  if (Array.isArray(obj)) {
    return obj.map(item => removeIds(item));
  } else if (typeof obj === 'object' && obj !== null) {
    delete obj.id;
    delete obj.sku_id;
    delete obj.spu_id;
    Object.keys(obj).forEach(key => {
      obj[key] = removeIds(obj[key]);
    });
  }
  return obj;
}

export const computeImageType = (url) => {
  if(!url) return ''
  const extension = url.split(".").pop().toLowerCase();
  return extension;
};